<template>
  <div class="app-container">
    <el-card>
      <el-input
        v-model="searchName"
        placeholder="昵称 | 班级 | 学号"
        style="width: 9rem;"
        @keyup.enter.native="userList"
        @input="userList"
      />
      <el-select
        v-model="selectDefunct"
        clearable
        placeholder="请选择状态"
        style="margin-left: 1rem"
        @change="userList"
      >
        <el-option
          v-for="item in defunctOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-date-picker
        v-model="dateRange"
        style="margin-left: 1rem"
        type="daterange"
        value-format="yyyy-MM-dd"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        @change="changeDate"
      />
      <el-button type="primary" icon="el-icon-plus" style="float: right" @click="dialogVisible=true">添加用户</el-button>
      <el-dialog
        title="用户信息"
        :destroy-on-close="true"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :visible.sync="dialogVisible"
        :show-close="false"
        top="3vh"
        width="50%"
        @close="userList"
      >
        <el-form :model="userForm" :rules="rules" label-width="60px">
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="userForm.email" />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="userForm.password" />
          </el-form-item>
          <el-form-item label="状态" prop="defunct">
            <el-switch v-model="userForm.defunct" />
          </el-form-item>
          <el-form-item label="昵称" prop="nick">
            <el-input v-model="userForm.nick" />
          </el-form-item>
          <el-row>
            <el-col :span="12">
              <el-form-item label="性别" prop="sex">
                <el-select v-model="userForm.sex" placeholder="请选择性别">
                  <el-option label="未知" value="0" />
                  <el-option label="男" value="1" />
                  <el-option label="女" value="2" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="角色" prop="roleId">
                <el-select v-model="userForm.roleId" placeholder="请选择角色">
                  <el-option
                    v-for="item in roles"
                    :key="item.roleId"
                    :label="item.roleName"
                    :value="item.roleId"
                    :disabled="item.defunct==='Y'"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="班级" prop="clbum">
            <el-input v-model="userForm.clbum" />
          </el-form-item>
          <el-form-item label="学号" prop="number">
            <el-input v-model="userForm.number" />
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible=false">取消</el-button>
          <el-button type="primary" @click="insertUser">保存</el-button>
        </span>
      </el-dialog>
    </el-card>
    <el-card style="margin-top: 1rem">
      <el-table :data="users" stripe>
        <el-table-column prop="email" label="邮箱" width="170px" />
        <el-table-column prop="nick" label="昵称" />
        <el-table-column prop="sex" label="性别">
          <template slot-scope="scope">
            {{ scope.row.sex===0?'未知':scope.row.sex===1?'男':'女' }}
          </template>
        </el-table-column>
        <el-table-column prop="clbum" label="班级">
          <template slot-scope="scope">
            {{ scope.row.clbum||'— —' }}
          </template>
        </el-table-column>
        <el-table-column prop="number" label="学号">
          <template slot-scope="scope">
            {{ scope.row.number||'— —' }}
          </template>
        </el-table-column>
        <el-table-column prop="ip" label="注册IP" />
        <el-table-column prop="regTime" label="注册时间" width="160px" />
        <el-table-column prop="defunct" label="状态">
          <template slot-scope="scope">
            <el-link :type="scope.row.defunct==='N'?'success':'danger'" @click="updateUserDefunct(scope.row)">
              {{ scope.row.defunct === 'N' ? 'Available' : 'Reserved' }}
            </el-link>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="margin-top: 20px;"
        background
        :current-page="currentPage"
        :page-sizes="[10, 25, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalNum"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
  </div>
</template>

<script>
import { insertUser, listRole, updateUserDefunct, userList } from '@/api/user'
import { validEmail } from '@/utils/validate'

export default {
  data() {
    const validateEmail = (rule, value, callback) => {
      if (!validEmail(value)) {
        callback(new Error('请输入正确的邮箱'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 8) {
        callback(new Error('请输入不小于8位的密码'))
      } else {
        callback()
      }
    }
    return {
      searchName: '',
      currentPage: 1,
      pageSize: 10,
      totalNum: 0,
      selectDefunct: '',
      dateRange: ['', ''],
      users: [],
      dialogVisible: false,
      defunctOptions: [{ value: 'N', label: '启用' }, { value: 'Y', label: '禁用' }],
      userForm: {
        email: '',
        password: '',
        defunct: false,
        nick: '',
        sex: '0',
        clbum: '',
        number: '',
        roleId: 1
      },
      roles: [{ roleId: 2, roleName: '用户', defunct: 'N' }],
      rules: {
        email: [{ required: true, trigger: 'blur', validator: validateEmail }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }]
      }
    }
  },
  created() {
    this.userList()
    this.listRole()
  },
  methods: {
    insertUser() {
      const form = new FormData()
      form.set('email', this.userForm.email)
      form.set('password', this.userForm.password)
      form.set('defunct', this.userForm.defunct ? 'Y' : 'N')
      form.set('nick', this.userForm.nick)
      form.set('sex', this.userForm.sex)
      form.set('roleId', this.userForm.roleId)
      form.set('clbum', this.userForm.clbum)
      form.set('number', this.userForm.number)
      insertUser(form).then(res => {
        this.$message.success(res.message)
        this.dialogVisible = false
        this.userList()
      })
    },
    updateUserDefunct(row) {
      const form = new FormData()
      form.set('userId', row.userId)
      form.set('defunct', row.defunct)
      updateUserDefunct(form).then(res => {
        this.$message.success(res.message)
        row.defunct = row.defunct === 'N' ? 'Y' : 'N'
      })
    },
    userList() {
      userList({
        name: this.searchName,
        defunct: this.selectDefunct,
        startDate: this.dateRange[0],
        endDate: this.dateRange[1],
        current: this.currentPage,
        size: this.pageSize
      }).then(res => {
        this.totalNum = Number(res.data.total)
        this.users = res.data.records
      })
    },
    changeDate(date) {
      if (date === null || date === undefined) {
        this.dateRange = ['', '']
      }
      this.userList()
    },
    listRole() {
      listRole({ current: 1, size: 1000000 }).then(res => {
        this.roles = res.data.records
      })
    },
    handleSizeChange(size) {
      this.pageSize = size
      this.userList()
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage
      this.userList()
    }
  }
}
</script>

<style scoped>

</style>
